<template>
  <div>
    <Button @click="userModalVisible=true" :icon="icon" >{{text}}</Button>
  <!--  <span @click="clearSelectData" class="clear">清空已选</span>
    <Collapse simple class="collapse">
      <Panel name="1">
        已选择
        <span class="select-count">{{selectUsers.length}}</span> 人
        <p slot="content">
          <Tag
            v-for="(item, i) in selectUsers"
            :key="i"
            :name="item.id"
            color="default"
            closable
            @on-close="handleCancelUser"
          >{{item.username}}</Tag>
        </p>
      </Panel>
    </Collapse> -->
    <Drawer title="选择用户" closable v-model="userModalVisible" width="800" draggable class-name="ivu-drawer-wrap1">
      <Form
        ref="searchUserForm"
        :model="searchUserForm"
        inline
        :label-width="55"
        class="search-form"
      >
        <Form-item label="产品名称" prop="username">
          <Input
            type="text"
            v-model="searchUserForm.username"
            clearable
            placeholder="产品名称"
            style="width: 200px"
          />
        </Form-item>
        <Form-item label="部门" prop="department">
          <department-choose @on-change="handleSelectDep" style="width: 200px" ref="dep"></department-choose>
        </Form-item>
        <Form-item style="margin-left:-35px;" class="br">
          <Button @click="handleSearchUser" type="primary" icon="ios-search">搜索</Button>
          <Button @click="handleResetUser">重置</Button>
        </Form-item>
      </Form>
      
      <Table highlight-row :loading="userLoading" border :columns="userColumns"  :data="userData" :height="height" ref="userTable" 
      @on-row-click="rowclick" @on-current-change="handleRowCh"
       @on-selection-change="handleSelectRow1"
       @on-select="handleSelectRow" @on-select-cancel="handleCancelRow"
      @on-select-all="handleSelectAll" @on-select-all-cancel="handleSelectAll"></Table>
      <Row type="flex" justify="end" class="code-row-bg page" style="margin: 10px 0;">
        <Page
          :current="searchUserForm.pageNumber"
          :total="totalUser"
          :page-size="searchUserForm.pageSize"
          @on-change="changeUserPage"
          @on-page-size-change="changeUserPageSize"
          :page-size-opts="[10,20,50]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
      <div class="my-drawer-footer">
        <!-- 已选择
        <span class="select-count">{{selectUsers.length}}</span> 人 -->
        <!-- <Button @click="clearSelectData" style="margin-left:10px">清空已选</Button> -->
        <Button @click="addperson" style="margin-left:10px">添加</Button>
        <Button @click="userModalVisible=false" type="primary" style="margin-left:10px">关闭</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
import { getUserListData } from "@/api/index";
import departmentChoose from "./department-choose";
export default {
  name: "userChoose",
  components: {
    departmentChoose
  },
  props: {
    text: {
      type: String,
      default: "添加"
    },
    icon: {
      type: String,
      default: "md-person-add"
    }
  },
  data() {
    return {
      height: 500,
      userLoading: true,
      userModalVisible: false,
      selectUsers: [],
      selectUsersdemo: [],
      searchUserForm: {
        username: "",
        type: "",
        status: "",
        pageNumber: 1, // 当前页数
        pageSize: 10, // 页面大小
        sort: "createTime", // 默认排序字段
        order: "desc" // 默认排序方式
      },
  
      userColumns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "产品",
          key: "name",
          width: 100,
          
        },
        {
          title: "产品型号",
          key: "name",
          width: 100,
          
        },
        {
          title: "产品编号",
          key: "name",
          width: 100,
          
        },
        {
          title: "产品颜色",
          key: "name",
          width: 100,
          
        },
        {
          title: "产品色号",
          key: "name",
          width: 100,
          
        },
        {
          title: "产品材质",
          key: "name",
          width: 100,
        },
        {
          title: "价格",
          key: "name",
          width: 100,
        },
         {
          title: "换算比率",
          key: "name",
          width: 100,
        },
        {
          title: "单台体积",
          key: "name",
          width: 100,
        },  {
          title: "单台净重",
          key: "name",
          width: 100,
        },
          {
          title: "产品单位",
          key: "name",
          width: 100,
        },
       
      ],
      userData: [],
      totalUser: 0,
      selectedIds: new Set(),//选中的合并项的id 
      selectedSum: 0, //选中的总数量
    };
  },
  methods: {
    handleSelectDep(v) {
      this.searchUserForm.departmentId = v;
    },
    changeUserPage(v) {
      this.searchUserForm.pageNumber = v;
      this.getUserDataList();
      
    },
    changeUserPageSize(v) {
      this.searchUserForm.pageSize = v;
      this.getUserDataList();
    },
   
    getUserDataList() {
      this.userLoading = true;
      getProductListData().then(res => {
        this.userLoading = false;
        if (res.success) {
          console.log("1111")
          this.userData = res.result.content;
          this.totalUser = res.result.totalElements;
           this.$nextTick(() => {//确保dom加载完毕
                   this.setChecked();
        });
        }
      });
     
    },
     handleSelectRow1(selection, index) {
      console.log(this.$refs.userTable.getSelection());
      this.selectUsers=this.$refs.userTable.getSelection();
    },
    handleSelectAll (selection) {
      // 取消全选 数组为空
      if (selection.length === 0) {
 
        let data = this.$refs.userTable.data
        data.forEach((item) => {
          if (this.selectedIds.has(item.id)) {
            this.selectedIds.delete(item.id)
          }
        })
      } else {
        selection.forEach(item => {
          this.selectedIds.add(item.id)
        })
      }
      //同步
      this.selectedSum = this.selectedIds.size
    },
    
    //  选中某一行
    handleSelectRow (selection,row) {
      this.selectedIds.add(row.id)
    },
    //  取消某一行
    handleCancelRow (selection,row) {
      this.selectedIds.delete(row.id)
    },
	
    // cy 给跨页丢失的选中行重新添加选中状态
    setChecked () {
      // 找到绑定的table的ref对应的dom，找到table的objData对象，objData保存的是当前页的数据
      let objData = this.$refs.userTable.objData
      console.log(objData)
      console.log(this.selectedIds)
      for (let index in objData) {
        if (this.selectedIds.has(objData[index].id)) {
          objData[index]._isChecked = true
        }
      }
    },

    handleRowCh(currentRow, oldCurrentRow){
      // console.log(currentRow)
      // console.log(oldCurrentRow);
//  this.$refs.userTable.toggleSelect(index);
    // let that = this;
    // let flag = true;
    // this.selectUsersdemo.forEach(e => {
    //   if (currentRow.id == e.id) {
    //     selectUsersdemo.splice(e)
    //     // flag = false;
    //   }
    // });
    // if (flag) {
    //     let u = {
    //       id: currentRow.id,
    //       username: currentRow.username
    //     };
    //     this.selectUsersdemo.push(u);
    //   }
    //   console.log(this.selectUsersdemo)
    },

    rowclick(data,index,event){
       console.log('当前行数据:' + data)
      // console.log('点击行号:' + index)
      // console.log('点击事件:' + event)
      this.$refs.userTable.toggleSelect(index);
    },
    handleSearchUser() {
      this.searchUserForm.pageNumber = 1;
      this.searchUserForm.pageSize = 9;
      this.getUserDataList();
    },
    handleResetUser() {
      this.$refs.searchUserForm.resetFields();
      this.searchUserForm.pageNumber = 1;
      this.searchUserForm.pageSize = 9;
      this.$refs.dep.clearSelect();
      this.searchUserForm.departmentId = "";
      // 重新加载数据
      this.getUserDataList();
    },
    setData(v) {
      this.selectUsers = v;
      this.$emit("on-change", this.selectUsers);
    },
    chooseUser(v) {
      // 去重
    },
    addperson(){
      //  this.selectUsersdemo.forEach(e => {
      //    this.selectUsers.push(e);
      //   });
        console.log(this.selectUsers)
        this.$emit("on-change", this.selectUsers);
        this.$Message.success(`添加用户成功`);
    },
    clearSelectData() {
      this.selectUsers = [];
      this.$emit("on-change", this.selectUsers);
    },
    handleCancelUser(e, id) {
      // 删除所选用户
      let newArray = [];
      this.selectUsers.forEach(e => {
        if (id != e.id) {
          newArray.push(e);
        }
      });
      this.selectUsers = newArray;
      this.$emit("on-change", this.selectUsers);
      this.$Message.success("删除所选用户成功");
    }
  },
  created() {
    // 计算高度
    this.height = Number(document.documentElement.clientHeight - 230);
    this.getUserDataList();
  }
};
</script>

<style lang="less">
.clear {
  font-size: 12px;
  margin-left: 15px;
  color: #40a9ff;
  cursor: pointer;
}
.collapse {
  font-size: 12px;
  margin-top: 15px;
  width: 500px;
}
.my-drawer-footer {
  z-index: 99;
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
.select-count {
  font-size: 13px;
  font-weight: 600;
  color: #40a9ff;
}
.ivu-drawer-wrap1{
  z-index: 1001;
}
</style>

